package com.nowcoder.community.until;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;


/**
 * @author: caoxinfang
 * @email: 2717176337@qq.com
 * @date: 2022/3/11 16:17
 */

// 发送邮件的工具类

@Component
public class MailClient {

    // 记录一些日志
    private static final Logger logger =  LoggerFactory.getLogger(MailClient.class);

    // 注入JavaMailSender
    @Autowired
    private JavaMailSender mailSender;

    // 注入发件人
    @Value("${spring.mail.username}")
    private String from;

    // 发给谁 邮件主题 内容
    public void sendMail(String to,String subject, String content){

        try {
            // creat对象
            MimeMessage message = mailSender.createMimeMessage();
            // 帮助类构建详细的方法
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);
            // 设置收件人
            helper.setTo(to);
            // 设置主推
            helper.setSubject(subject);
            // 设置内容 不加参数认为是普通文本 文字 加上支持html文本
            helper.setText(content,true);
            // 发送出去
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            // 异常日志
            logger.error("发送邮件失败:"+e.getMessage());
        }

    }


}
